#include <cstdio>
#include <unistd.h>

#include "stringutil.h"
#include "httputil.h"

#include "messageheader.h"

void MessageHeader::appendField(const string& fieldName, const string& _fieldValue) {
    string fieldValue = stringutil::strip(_fieldValue);
    if (isFieldExists(fieldName))
        m_fields[fieldName] += " ," + fieldValue;
    else
        m_fields[fieldName] = fieldValue;
}

bool MessageHeader::isFieldExists(const string& fieldName) const {
    return m_fields.find(fieldName) != m_fields.end();
}

string MessageHeader::getFieldValue(const string& fieldName) const {
    if (!isFieldExists(fieldName))
        return "";
    return m_fields.find(fieldName)->second;
}

void MessageHeader::print(FILE* file) const {
    NameValueMap::const_iterator it;
    for (it = m_fields.begin(); it != m_fields.end(); ++it) {
        fprintf(file, "%s : %s\r\n",
                it->first.c_str(), it->second.c_str());
    }
}

void MessageHeader::printfd(int fd) const {
    NameValueMap::const_iterator it;
    for (it = m_fields.begin(); it != m_fields.end(); ++it) {
        string output = it->first + " : " + it->second + "\r\n";
        write(fd, output.data(), output.length());
    }
}

bool MessageHeader::parseAppend(const string& str) {
    // TODO: Make it not that naive...
    size_t pos = str.find(':');
    if (pos == string::npos)
        return false;
    string fieldName = string(str, 0, pos);
    string fieldValue = string(str, pos+1);
    appendField(fieldName, fieldValue);
    return true;
}

bool MessageHeader::parseHeader(int fd)
{
    bool eof = false;
    string str;bool success;
    while (true) {
        success = HTTPUtil::readline(str, &eof, fd);
        if (!success)
            return false;
        if (str == "" || str == "\r") // blank line
            return true;
        if (!parseAppend(str))
            return false;
        if (eof)
            return true;
    }
}

void MessageHeader::clear() {
    m_fields.clear();
}
